<template>
    <div class="uc">
        <div class="word">用户信息</div>
        <el-form  label-width="100px" class="demo-ruleForm">
            <div style="text-align: center; margin-bottom: 30px">
                <el-avatar :src="user.avatar+'?n='+$store.state.timestamp" :size="110"></el-avatar>
                <el-upload
                        class="upload-demo"
                        :action="this.$config.baseURL+'/user/avatar'"
                        :headers="headers"
                        name="file"
                        :limit="1"
                        :show-file-list="false"
                        :on-exceed="handleExceed"
                        :on-success="uploadSuccess"
                        :file-list="fileList"
                        :before-upload="beforeUploadAvatar">
                    <el-button size="small" type="primary">修改头像</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且大小不超过2Mb</div>
                </el-upload>
                <!--action:上传的地址；  name:上传的文件字段名；  headers:设置上传的请求头部；-->
            </div>
            <el-form-item label="用户名">
                <el-input v-model="user.username" maxlength="15" show-word-limit></el-input>
                <span class="mod" @click="updateUsername">修改</span>
            </el-form-item>
            <el-form-item label="昵称">
                <el-input v-model="user.nickname" maxlength="8" show-word-limit></el-input>
                <span class="mod" @click="updateNickname">修改</span>
            </el-form-item>
            <div style="display: flex;padding-left: 100px">
                <div class="pass" @click="dialogVisible=true">修改密码</div>
                <div class="pass" @click="dialogVisible_delete=true">注销账号</div>
            </div>
        </el-form>

        <!--修改密码对话框-->
        <el-dialog title="修改密码" :visible.sync="dialogVisible" width="30%" :before-close="beforeClose"
                   :modal-append-to-body="false" :close-on-click-modal="false" :modal="false">
            <el-form :model="passForm" status-icon :rules="rules" ref="passForm" label-width="100px">
                <el-form-item label="当前密码" prop="oldPassword">
                    <el-input type="password" v-model="passForm.oldPassword" autocomplete="off" show-password></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input type="password" v-model="passForm.newPassword" autocomplete="off" show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPassword">
                    <el-input type="password" v-model="passForm.checkPassword" autocomplete="off" show-password></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="updatePassword('passForm')">提交</el-button>
                    <el-button @click="resetForm('passForm')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!--注销账号对话框-->
        <el-dialog title="请输入密码进行确认" :visible.sync="dialogVisible_delete" width="430px" :before-close="beforeClose"
                   :modal-append-to-body="false" :close-on-click-modal="false" :modal="false">
            <el-form :model="deleteForm" status-icon :rules="rules" ref="deleteForm" label-width="100px">
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="deleteForm.password" autocomplete="off" show-password></el-input>
                </el-form-item>
                <el-form-item>
                    <el-popconfirm title="账号注销后，与之相关的所有内容都会被清除，确定注销吗？" @confirm="deleteUser">
                        <el-button type="primary" slot="reference">提交</el-button>
                    </el-popconfirm>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "UserCenter",
        data(){
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.passForm.newPassword) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                user: {},
                headers:{Authorization:localStorage.getItem('token')},
                fileList: [],
                passForm: {
                    oldPassword: '',
                    newPassword: '',
                    checkPassword: ''
                },
                deleteForm:{
                  password:''
                },
                dialogVisible: false,
                dialogVisible_delete: false,
                rules: {
                    oldPassword: [
                        { required: true, message: '请输入当前密码', trigger: 'blur' },
                        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                    ],
                    newPassword: [
                        { required: true, message: '请输入新密码', trigger: 'blur' },
                        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                    ],
                    checkPassword: [
                        { required: true, validator: validatePass, trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                    ]
                }
            }
        },
        methods: {
            getUserInfo(){
                this.$axios.post('/loginbytoken').then(res=>{
                    this.$store.commit('set_userInfo',res.data.data);
                    this.user = this.$store.state.userInfo;
                    this.$store.state.timestamp = Date.now()
                })
            },

            //文件超出个数限制时的钩子
            handleExceed(files, fileList) {
                this.$message.warning(`文件数量超出限制`);
            },
            //头像上传之前检查格式和大小
            beforeUploadAvatar(file){
                if(!localStorage.getItem('token')){
                    this.headers = {};
                }
                let isJPG = file.type === 'image/jpeg';
                let isPNG = file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG && !isPNG) {
                    this.$message.error('上传头像图片只能是 JPG或PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return (isJPG||isPNG) && isLt2M;
            },
            //头像上传成功后重新获取用户信息
            uploadSuccess(){
                this.getUserInfo();
                this.$message.success('头像更换成功！');
                this.fileList = []
            },
            updateUsername(){
                if(this.user.id == '12'){
                    this.$message.warning('公共账号的用户名不可修改')
                    return
                }
                this.$axios.post('/user/updateUsername', this.user,
                    {headers:{'Content-Type' : 'application/x-www-form-urlencoded'}}).then(res => {
                    if(res.data.code == 200){
                        this.$message.success(res.data.data)
                        this.getUserInfo()
                    }
                })
            },
            updateNickname(){
                this.$axios.post('/user/updateNickname', this.user,
                    {headers:{'Content-Type' : 'application/x-www-form-urlencoded'}}).then(res => {
                    if(res.data.code == 200){
                        this.$message.success(res.data.data)
                        this.getUserInfo()
                    }
                })
            },
            //修改密码提交
            updatePassword(formName) {
                this.$refs[formName].validate((valid) => {
                    if(this.user.id == '12'){
                        this.$message.warning('公共账号的密码不可修改')
                        return
                    }
                    if (valid) {
                        this.$axios.post('/user/updatePassword', this.passForm).then(res => {
                            if(res.data.code == '200'){
                                this.resetForm('passForm')
                                this.dialogVisible = false
                                this.$store.commit('set_needLogin', {flag:true, msg:'密码修改成功，请重新登陆'})
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                if(this.$refs[formName]!=undefined){
                    this.$refs[formName].resetFields()
                }
            },
            beforeClose(done){
                done()
                this.resetForm('passForm')
                this.resetForm('deleteForm')
            },
            deleteUser(){
                this.$refs['deleteForm'].validate((valid) => {
                    if(this.user.id == '12' || this.user.id == '1'){
                        this.$message.warning('该账号不可注销')
                        return
                    }
                    if (valid) {
                        this.deleteForm.userId = this.$store.state.userInfo.id
                        console.log(this.deleteForm)
                        this.$axios.post('/user/delete',this.deleteForm,
                            {headers:{'Content-Type' : 'application/x-www-form-urlencoded'}}).then(res=>{
                            if(res.data.code === 200){
                                this.$message.success(res.data.data)
                                this.$store.commit('reset_data')
                                this.$router.push('/index')
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
        },
        created() {
            this.user = {...this.$store.state.userInfo};    //对象复制，直接=是赋地址

            if(!this.$store.state.userInfo){ //未登陆
                this.$router.push('/blank')
                this.$store.commit('set_needLogin',{flag: true,msg: '您还未登录，无法进入个人中心'})
            }
        }
    }
</script>

<style scoped>
    .uc{
        width: 500px;
        margin: 0 auto 20px auto;
        border: 1px solid #ddd;
        min-height: 595px;
        background-color: white;
    }
    .el-form{
        max-width: 400px;
        margin: 0 auto;
    }
    .word{
        border-bottom: 1px solid #ddd;
        color: black;
        text-align: center;
        padding: 12px;
        margin-bottom: 20px;
        font-size: 17px;
    }
    .pass{
        color: #00a1d6;
        text-align: center;
        cursor: pointer;    /*鼠标变小手*/
        margin-right: 15px;
    }
    .el-input{
        width: 250px;
    }
    .mod{
        margin-left: 8px;
        cursor: pointer;    /*鼠标变小手*/
        color: #00a1d6;
    }
</style>
